/**
 * 数据范围公共方法 edit view search
 * @version V1.0
 */
var Program = {
	/**
	 * 渲染维度项
	 * divId 需要渲染到的divId
	 * forWhat 必须参数 edit：编辑 view：查看 search：搜索
	 * programId 需要加载已有值是填写此值
	 */
	renderItems : function(divId,forWhat,programId,programNameInputId,programDescInputId){
		Program._getTemplate(forWhat,divId);
		var html = '<ui>'+Ccay.UI.tmplList(Program._getTemplate(forWhat,divId),Program.getDimensionConfigs())+'</ui>';
		$("#"+divId).html(html);
		if(programId){
			Program._loadData(programId,divId,programNameInputId,programDescInputId);
		}
	},
	/**
	 * 获取json对象
	 * divId 渲染时使用的divId
	 */
	getDimensionJson : function(divId){
		var dimensions = {};
		var configs = Program.getDimensionConfigs();
		for(var j=0;j<configs.length;j++){
			var config = configs[j];
			var keyStr = $("#"+divId+"_"+config.dimensionName+"_keys").val();
			if(!keyStr){
				continue;
			}
			var keys =keyStr.split(",");
			var keyValuePairList = [];
			for(var i=0;i<keys.length;i++){
				keyValuePairList.push({key:keys[i]});
			}
			dimensions[""+config.dimensionName] = keyValuePairList;
		}
		return dimensions;
	},
	/**
	 * 获取IGrid编辑器对象（联想弹出框）
	 */
	suggestPopupEditOpt : function(){
		//debugger;
		return {
				suggestOp : {
					ajax : {
						type:'POST',
						url: "services/manage/security/programManage/findPagedPrograms/page/80/1"
					},
					fieldMapper : {
						programName : $i18n("ccay.common.label.name"),
						description : $i18n("ccay.common.label.desc")
					}
				},
				popOp : {
					title : $i18n("ccay.datascope.label.name"),
					width : 840,
					height : 445,
					ajax : {
						type:'POST',
						url: 'services/manage/security/programManage/findPagedPrograms/page/${pageSize}/${curPage}'
					},
					uniqueKey : "programId",
					columns : [
						{id : 'programId',hidden : true},
						{header : 'ccay.security.label.datascope',id:'programName',width:100, showTip:true,hidden:false,isCondition:true},
						{header :'ccay.program.label.description',id:'description',width:100, showTip:true,hidden:false,isCondition:true}
						],
					igrid : true,
					historySupport : false,
					reSizable : true,
					// 设置弹出框子公司igrid列属性
					leftTableOptions : {
						// 内容超出时才显示Tip，否则不显示
						showColumnIcon : false,
						showSeq : false,
						clickRow2Check : true,
						showOverflow : true,
						// 冻结列
						colsort : false,
						// 设置igrid的宽度是否进行百分比设置，默认为false
						percentWidth : true,
						// 设置igrid的表头是否进行Tip显示，默认为false
						headTip : true,
						// 设置igrid的表头内容是否进行折行显示，默认为true
						wrapHead : false,
						// 设置igrid的单元格内容是否进行折行显示，默认为false;在百分比设置下，即percentWidth:true，wrap默认为true，即折行显示
						wrap : false,
						allowSort : false,
						pagerOp : {
							// 设置igrid的分页信息的配置
							pageInf : {
								// 设置igrid每页显示8条数据
								pageSize : 10,
								// 设置igrid初始化时显示第2页的数据
								curPage : 1
							},
							// 设置iGrid分页栏里的每页显示的数据条数下拉框的选项（包含默认的选项）
							pageSizes : [10, 15, 20, 50, 100]
						},
						fnBeforeRequest : function(opt) {
							opt.ajax.data.dimensions = Program.getDimensionJson("programPopupItemSearchId");
						}
					},
					condRender : function() {
						return ""+
						"<div class='ccay-form-body'>"+
							"<ul>"+
								"<li class='ccay-form-row'>"+	
									"<samp class='init i18n' i18nKey='ccay.security.label.datascope'/></samp>"+
									"<span class='ccay-form-input'>"+
										"<input type='text' name='programName'/>"+
									"</span>"+
								"</li>"+
								"<li class='ccay-form-row'>"+	
									"<samp class='init i18n' i18nKey='ccay.common.label.description'/></samp>"+
									"<span class='ccay-form-input'>"+
										"<input type='text' name='description'/>"+
									"</span>"+	
								"</li>"+
								"<li id='morecondition' class='ccay-form-row  ccay-form-more'  style='width:100%;'>"+
							  		"<a onclick='Ccay.Common.toggle(this,\"#programPopupItemSearchId\")' i18nKey='ccay.common.label.moreSearchConditions' class='i18n'></a>"+
							 	"</li>"+
							"</ul>"+
						"</div>"+
						"<div id='programPopupItemSearchId' class='ccay-form-custom' style='display:none;'>";
					},
					initRender : function() {
						Program.renderItems("programPopupItemSearchId","search");
					}
				},
				displayField : "programName",
				valueField : "programId"
			};
	},
	_loadData : function(programId,divId,programNameInputId,programDescInputId){
		Ccay.doGet({
 			async:false,
 			url:"services/manage/security/programManage/findDimensionValues/"+programId,
 			success:function(vo){
 				if(programNameInputId){
 					$("#"+programNameInputId).val(vo.programName);
 				}
 				if(programNameInputId){
 					$("#"+programDescInputId).val(vo.description);
 				}
 				for(dimension in vo.dimensions){
 					var keys = [];
 					var values = [];
 					for(var i=0;i<vo.dimensions[dimension].length;i++){
 						keys.push(vo.dimensions[dimension][i].key);
 						values.push(vo.dimensions[dimension][i].value);
 					}
 					$("#"+divId+"_"+dimension+"_keys").val(keys.join(","));
 					$("#"+divId+"_"+dimension+"_values").val(values.join(","));
 					$("#"+divId+"_"+dimension+"_values").attr("title",values.join(","));
 				}
 			}			
 		});
	},
	//弹出窗口选择
	_popup : function(dimension,divId){
		var popupBean = Program._popupBean
		popupBean.servicePath="services/manage/security/programManage/findDimensionValues/"+dimension;
		popupBean.callback = function(data){
			var keys = [];
			var values = [];
			$.each(data, function(i, v) {
				keys.push(this.key);
				values.push(this.value);
			});
			$("#"+divId+"_"+dimension+"_values").val(values.join(","));
			$("#"+divId+"_"+dimension+"_keys").val(keys.join(","));
			$("#"+divId+"_"+dimension+"_checkbox").attr("checked",false);
			
		};
		var selectedItems = [];
		var selectKeys = $("#"+divId+"_"+dimension+"_keys").val();
		if(selectKeys !="CURRENT_VALUE"){
			popupBean.selectedItems = selectKeys ? selectKeys.split(",") : [];
		}
		var dimensionObj = this.getDimensionConfitObject(dimension);
		Ccay.Component.popup(popupBean, $i18n(dimensionObj.dimensionDisplayName),selectedItems && true,885,450);
	},
	/**
	 * 获取维度配置。如果没有，则先加载再返回
	 */
	getDimensionConfigs : function(){
		if(!Program._dimensionConfigs){
			Ccay.doGet({
	 			async:false,
	 			url:"services/manage/security/programManage/findDimensionConfigs",
	 			data :"",
	 			success:function(dimensions){
	 				Program._dimensionConfigs = dimensions;
	 			}			
	 		});
		}
		return Program._dimensionConfigs;
	},
	/**
	 * 根据维度名获取维度配置
	 */
	getDimensionConfitObject : function(dimension){
		var configs = Program.getDimensionConfigs();
		for(var i=0;i<configs.length;i++){
			if(configs[i].dimensionName == dimension){
				return configs[i];
			}
		}
		return null;
	},

	/**
	 * 弹出窗口条件输入HTML
	 */
	_conditionHtml : 
		"<ul class='ccay-horRow' style='display:inline-block;margin-bottom:10px;'>"+
	        "<li class='ccay-horRow-item'>"+$i18n("名称")+"：</li>"+
	        "<li class='ccay-horRow-item' ><input type='text' id='value' name='value' /></li>"+
	        "<li class='ccay-horRow-item' >&nbsp;&nbsp;&nbsp;&nbsp;"+$i18n("值")+"：</li>"+
	        "<li class='ccay-horRow-item' ><input type='text' id='key' name='key' /></li>"+
	    "</ul></br>",
	/**
	 * 弹出窗口列设置
	 */
	_selectCurrent : function(dimension,divId){
		$("#"+divId+"_"+dimension+"_values").val("CURRENT_VALUE");
		$("#"+divId+"_"+dimension+"_keys").val("CURRENT_VALUE");
	},
	_popupBean : {
			leftTableOptions: {
				width:450,
				height:290,
				showSeq : false,
				headTip:true,
				wrapHead:false,
				showOverflow:true,
				colsort:false,
				allowSort:false,
				clickRow2Check:true
			},
			rightTableOptions:{
				width:450,
				height:290,
				showSeq : false,
				headTip:true,
				wrapHead:false,
				showOverflow:true,
				colsort:false,
				allowSort:false,
				clickRow2Check:true
			},
			maxHeight:800,
			igrid :true,
			/* service的服务路径维度不同将重新初始化*/
			servicePath : "",
			/* 查询数据中的一个唯一键属性名，区分已选数据，多选的时候是必须的 */
			uniqueKey : "key",
			historySupport:false,
			/* 显示列头定义 */
			columns : [
	            {header:$i18n("名称"),width:250, id: 'value',isCondition:true,showTip:true},
	            {header:$i18n("值"),width:140, id: 'key',isCondition:true,showTip:true}
			],
			pageSize:10,
			pageSizeList:[10,15,20,50,100],
			condRender : function(){return	Program._conditionHtml},
			dialogOp:{
				maxHeight:800
			},
			initRender : function(divSelector){}
	},
	/**
	 * 维度配置缓存
	 */
	_dimensionConfigs : null,
	
	/**
	 * 获取模板
	 */
	_getTemplate : function(/*String */forWhat,divId){
		//如果是编辑则进行渲染当前值的按钮判断
		var currentValTemp =  forWhat == "edit" ? 
				"<% if(currentDimension || dataProviderBeanName == 'SYS_USER_PROVIDER'){ %>"+
		        "<input type='radio' class='noBorder' id='${dimensionName}_checkbox' onclick='Program._selectCurrent(\"${dimensionName}\",\""+divId+"\")'>当前值"+
		        "<% } %>" : "";
		//如果是编辑或查看时的placeholder
		var placeholder = (forWhat == "edit" || forWhat == "view") ? "ALL" : "";
		var openBtn = forWhat != "view" ?  "<input type='button' class='jbutton popup-trigger' value='...' onclick='Program._popup(\"${dimensionName}\",\""+divId+"\")'>" : ""
		return ""+
		"<li class='ccay-form-row'>"+
		    "<samp>${dimensionDisplayName}</samp>"+
		    "<span class='ccay-form-input'>"+
		    	currentValTemp+
		        "<input type='text' id='"+divId+"_${dimensionName}_values' class='popup-input' style='"+(forWhat == "view" ? "width:93%;" : "width:370px")+"' readonly='readonly' placeholder='"+placeholder+"' >"+
		        "<input type='hidden' id='"+divId+"_${dimensionName}_keys' readonly='readonly' style='background-color:gray'>"+
		        openBtn+
		    "</span>"+
		"</li>";
	}

}
